﻿using System;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Ecobee.Net
{
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum AuthorizationScope
	{
		None,
		SmartRead,
		SmartWrite
	}

	/// <summary>
	/// 
	/// </summary>
	public abstract class SecurityObject : ApiObject
	{
		public enum ExpirationUnit
		{
			Seconds,
			Minutes
		}

		private int _expiresIn = 0;

		public SecurityObject()
			: base()
		{
		}

		public SecurityObject(Api api)
			: base(api)
		{
		}

		// ***
		// *** Custom properties
		// ***
		private TimeSpan _lifetime = TimeSpan.Zero;
		private DateTime _timeStamp = DateTime.MinValue;

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty(PropertyName = "expires_in")]
		public int ExpiresIn
		{
			get
			{
				return _expiresIn;
			}
			set
			{
				_expiresIn = value;
			}
		}

		/// <summary>
		/// The amount of time until this security object expires.
		/// </summary>
		[JsonIgnore]
		public TimeSpan Lifetime
		{
			get
			{
				TimeSpan returnValue = TimeSpan.Zero;

				if (this.OnGetExpirationUnit() == ExpirationUnit.Seconds)
				{
					returnValue = TimeSpan.FromSeconds(this.ExpiresIn);
				}
				else
				{
					returnValue = TimeSpan.FromMinutes(this.ExpiresIn);
				}

				return returnValue;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[JsonProperty(PropertyName = "timestamp")]
		public DateTime TimeStamp
		{
			get
			{
				return _timeStamp;
			}
			internal set
			{
				_timeStamp = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[JsonIgnore]
		public DateTime ExpiresAt
		{
			get
			{
				return this.TimeStamp.Add(this.Lifetime);
			}
		}

		protected override void OnLoadFrom(object dataObject)
		{
			this.TimeStamp = DateTime.Now;
			base.OnLoadFrom(dataObject);
		}

		protected virtual ExpirationUnit OnGetExpirationUnit()
		{
			return ExpirationUnit.Minutes;
		}
	}
}
